//
//  TSMainViewController.swift
//  TSProfitProject
//
//  Created by TmmmS on 2019/10/29.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import MJRefresh

let OYMultipleTableSource1 = "OYMultipleTableSource1"
let OYMultipleTableSource2 = "OYMultipleTableSource2"

class TSMainViewController: TSBaseViewController {

    private let tableHeaderViewH = STATUSBAR_HEIGHT + 174
    private var tableController : TSBaseTableViewController!
    private var dataSource = Array<TSMainPageModel>()
    private var bannderArray = Array<TSBannerModel>()
    private var AnnouncementArray = Array<TSAnnouncementModel>()
    private var headerView : TSMainHeaderView!
    
    private lazy var sectionHeaderView : TSMainSectionHeaderView = {
        var header = TSMainSectionHeaderView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - CGFloat(T_NAVBARHEIGHT)))
        header.delegate = self
        return header
    }()
    
    private lazy var footerView : UIView = {
        let imgScale : CGFloat = 345.0 / 120
        var footer = UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 2*10+SCREEN_WIDTH / imgScale))
        footer.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#F7F7F7")
        
        let container = UIView.init(frame: CGRect(x: 0, y: 10, width: SCREEN_WIDTH, height: SCREEN_WIDTH / imgScale))
        container.backgroundColor = WHITE_COLOR
        footer.addSubview(container)
        
        let img = UIImageView.init(image: UIImage(named: "main_advertise"))
        container.addSubview(img)
        img.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview().inset(15)
            make.top.equalToSuperview()
            make.height.equalTo(SCREEN_WIDTH / imgScale)
        }
        
        return footer
    }()

    @objc private func refreshDatas() {
        self.getRequest()
    }
    
    deinit {
        self.navigationController?.delegate = nil
    }
}

extension TSMainViewController : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let offsetY = scrollView.contentOffset.y + scrollView.contentInset.top

        let minAlphaOffset : CGFloat = 0;
        let maxAlphaOffset : CGFloat = 40;
        
        let alpha = (offsetY - minAlphaOffset) / (maxAlphaOffset - minAlphaOffset);
        if (alpha >= 0.6) {
            if #available(iOS 13, *) {
                UIApplication.shared.statusBarStyle = .darkContent
            } else {
                UIApplication.shared.statusBarStyle = .default
            }
        } else if (alpha <= 0.2) {
            UIApplication.shared.statusBarStyle = .lightContent
        }
    }
}

extension TSMainViewController : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let imgScale : CGFloat = 167.0 / 130
        let collectionW = CGFloat(SCREEN_WIDTH - 2*15)
        let itemSpacing : CGFloat = 10
        let itemW = (collectionW - itemSpacing) * 0.5
        let itemH = itemW / imgScale
        return itemH + 47
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        110
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return sectionHeaderView
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 20))
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        20
    }
}

extension TSMainViewController : UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSGameTableViewCell.self)) as? TSGameTableViewCell
        
        cell?.delegate = self
        
        cell?.setupCell(array: self.dataSource)
        
        return cell!
    }
    
}

//MARK: - TSGameTableViewCellDelegate
extension TSMainViewController : TSGameTableViewCellDelegate {
    
    func didClickCell(model: TSMainPageModel) {
        
        let vc = TSMainDetailViewController.init()
        vc.identifier = model.identifier
        navigationController?.pushViewController(vc, animated: true)

    }
}

// MARK: - Network Request
extension TSMainViewController {
    
    func requestUserInfo() {
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.getUserInfo, showHUD: true, success: { (data) in
            
            let responseDic = data as? NSDictionary
            var model = TSLoginModel.deserialize(from: responseDic)!
            model.token = TSLoginManager.shared.token
            model.user_id = TSLoginManager.shared.user_id
            TSLoginManager.shared.setUserModel(model: model)
            
            self.getRequest()
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    func getRequest(){
        
        let queue = DispatchQueue.init(label: "getCount")
        let group = DispatchGroup()
        
        queue.async(group: group, execute: {
            group.enter()
            
            self.requestNoticeDatas {
                group.leave()
            }
        })
        
        queue.async(group: group, execute: {
            group.enter()
            
            self.requestBannerDatas {
                group.leave()
            }
        })
        
        group.notify(queue: queue){
            DispatchQueue.main.async {
                
                CBToast.hiddenToastAction()
                self.tableController.tableView.mj_header.endRefreshing()
                
                self.sectionHeaderView.setupNoticeView(array: self.AnnouncementArray)
                self.headerView.setupHeaderView(array: self.bannderArray)

            }
        }
    }
    
    func requestNoticeDatas(completeCallback: @escaping() -> Void) {
        
        TSNetworkManager.request(TMSNetworkTools.getNotice, showHUD: false, success: { (data) in
        
            completeCallback()
            
            self.AnnouncementArray.removeAll()
            
            let array = data as? Array<Dictionary<String, Any>>
            for item in array ?? Array() {
                let model = TSAnnouncementModel.deserialize(from: item)
                if let noticeModel = model {
                    self.AnnouncementArray.append(noticeModel)
                }
            }
            
        }) { (error) in
            
            completeCallback()
        }
    }
    
    func requestBannerDatas(_ completeCallback: @escaping() -> Void) {
        TSNetworkManager.request(TMSNetworkTools.getBanner, showHUD: false, success: { (data) in
            
            completeCallback()
            
            self.bannderArray.removeAll()
            let array = data as? Array<Dictionary<String, Any>>
            for item in array ?? Array() {
                let model = TSBannerModel.deserialize(from: item)
                if let bannerModel = model {
                    self.bannderArray.append(bannerModel)
                }
            }
            
        }) { (error) in
            
            completeCallback()
        }
    }
}

// MARK: - TSMainSectionHeaderViewDelegate
extension TSMainViewController : TSMainSectionHeaderViewDelegate {
    
    func didClickHeaderEntry(title: String) {
        
        switch title {
        case "充值":
            navigationController?.pushViewController(TSRechargeViewController(), animated: true)
        case "提现":
            navigationController?.pushViewController(TSWithDrawViewController(), animated: true)
        case "额度转换":
            navigationController?.pushViewController(TSLimitConvertViewController(), animated: true)
        case "钱包":
            let vc = TSWalletViewController()
            navigationController?.pushViewController(vc, animated: true)

        default:
            break
        }
    }
    
}

// MARK: - LifeCycle
extension TSMainViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationController?.delegate = self

        configViews()
        handleDatas()
        
        requestUserInfo()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        scrollViewDidScroll(tableController.tableView)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIApplication.shared.statusBarStyle = .lightContent
    }
}

// MARK: - Initialize
extension TSMainViewController {
    
    private func configViews() {

        UIApplication.shared.statusBarStyle = .lightContent
        
        tableController = TSBaseTableViewController.init(style: .grouped)
        tableController.shouldDisplayEmptyAlert = false
        tableController.tableView.backgroundColor = WHITE_COLOR
        tableController.tableView.contentInset = UIEdgeInsets(top: tableHeaderViewH, left: 0, bottom: 10, right: 0)
        tableController.tableView.delegate = self
        tableController.tableView.dataSource = self
        tableController.tableView.showsVerticalScrollIndicator = false
        tableController.tableView.separatorStyle = .none
        tableController.tableView.tableFooterView = self.footerView
        tableController.tableView.register(TSGameTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(TSGameTableViewCell.self))
        view.addSubview(tableController.tableView)
        tableController.tableView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().inset(T_TABBARHEIGHT)
        }
        
        headerView = TSMainHeaderView.init(frame: CGRect(x: 0, y: -tableHeaderViewH, width: SCREEN_WIDTH, height: tableHeaderViewH))
        
        tableController.tableView.addSubview(headerView)
        tableController.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refreshDatas))
        tableController.tableView.mj_header.ignoredScrollViewContentInsetTop = tableHeaderViewH
    }
    
    private func handleDatas() {
        
        let title = ["北京赛车 20分钟一期", "幸运飞艇 5分钟一期"]
        let img = ["main_cell_race", "main_cell_yacht"]
        let identifier = ["OYMultipleTableSource1", "OYMultipleTableSource2"]
        
        for index in 0..<2 {
            
            var model = TSMainPageModel.init()
            model.title = title[index]
            model.imageName = img[index]
            model.identifier = identifier[index]
            dataSource.append(model)
        }
        tableController.tableView.reloadData()
    }
}

extension TSMainViewController : UINavigationControllerDelegate {
    
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {

        let isShowHomePage = viewController.isKind(of: TSMainViewController.self)
        self.navigationController?.setNavigationBarHidden(isShowHomePage, animated: false)
    }
}
